﻿using AIO.Entity.Base;
using AIO.IService.Base;
using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;

namespace AIO.Service.Base
{
    /// <summary>
    /// 基础仓库
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        /// <summary>
        /// 数据上下文
        /// </summary>
        private ApiDBContext _BaseContext { get; set; }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dBContext"></param>
        /// <exception cref="ArgumentNullException"></exception>
        public BaseRepository(ApiDBContext dBContext)
        {
            _BaseContext = dBContext ?? throw new ArgumentNullException(nameof(dBContext));
        }
        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public void Create(T entity)
        {
            _BaseContext.Set<T>().Add(entity);
        }
        /// <summary>
        /// 更新数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public void Update(T entity)
        {
            _BaseContext.Set<T>().Update(entity);
        }

        /// <summary>
        /// 根据ID删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public void Delete(T entity)
        {
            _BaseContext.Set<T>().Remove(entity);
        }
        /// <summary>
        /// 获取所有(合法数据)
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public IQueryable<T> GetAll(Expression<Func<T, bool>> expression)
        {
            return _BaseContext.Set<T>().Where(expression).AsNoTracking();
        }
        /// <summary>
        /// 获取所有(合法数据)
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<List<T>> GetAllAsync(Expression<Func<T, bool>> expression)
        {
            return _BaseContext.Set<T>().Where(expression).ToListAsync();
        }
        /// <summary>
        /// 获取所有数据,包括异常数据
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public IQueryable<T> GetAllNoBy()
        {
            return _BaseContext.Set<T>().AsNoTracking();
        }
        /// <summary>
        /// 获取所有数据,包括异常数据
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<List<T>> GetAllNoByAsync()
        {
            return _BaseContext.Set<T>().ToListAsync();
        }


    }
}
